package com.hava.homework.repository;

import com.hava.homework.entity.UserBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.List;

/**
 * Created by yanfa on 2016/10/27.
 */
@Repository
public class UserBalanceJdbcTemplateDao implements UserBalanceDaoInterface {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<UserBalance> findAll() {
        return this.jdbcTemplate.query("SELECT * FROM UserBalance",new BeanPropertyRowMapper(UserBalance.class));
    }

    public void addMoney(Long userId, double count){
        this.jdbcTemplate.update("UPDATE UserBalance SET balance=balance+? WHERE userId=?",count,userId);
    }

    public void subMoney(Long userId,double count){
        this.jdbcTemplate.update("UPDATE UserBalance SET balance=balance-? WHERE userId=?",count,userId);
    }

    // srcUserId及targetUserId为转帐用户标识
    public void transferMoney(Long srcUserId, Long targetUserId, double count){
        System.out.println("transferMoney");
        this.subMoney(srcUserId,count);
        throwException();
        this.addMoney(targetUserId,count);
    }

    private void throwException() {
        throw new RuntimeException("Throw Exception");
    }
}
